package com.google.code.server4j.connector.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;

import com.google.code.server4j.connector.HttpInfo;
import com.google.code.server4j.connector.HttpProcessor;
import com.google.code.server4j.connector.Request;
import com.google.code.server4j.connector.Response;
import com.google.code.server4j.handler.Handler;
import com.google.code.server4j.util.BaseLifeCycle;
import com.google.code.server4j.util.Log;

public class BioHttpProcessor extends BaseLifeCycle implements HttpProcessor {

	private Handler handler;
	private boolean keepAlive = true;
	private int socketTimeOut = 30;
	
	private BioRequestParser parser;
	private HttpInfo httpInfo = new HttpInfo();
	private String context;
	
	public void setHandler(Handler handler) {
		this.handler = handler;
	}

	public void setSocketTimeOut(int socketTimeOut) {
		this.socketTimeOut = socketTimeOut;
	}

	@Override
	protected void doInit() throws Exception {
		parser = new BioRequestParser(httpInfo);
		super.doInit();
	}


	@Override
	public boolean process(Socket socket) {
		try {
			while(keepAlive) {
				socket.setSoTimeout(socketTimeOut);
				InputStream is = socket.getInputStream();
				OutputStream os = socket.getOutputStream();
				Request req = new Request(is);
				Response resp = new Response(os);
				
				parser.parseRequestLine(is);
				context = httpInfo.getUri();
				Log.debug(httpInfo.toString());
//				parseRequestLine(is);
//				Log.debug(method+" "+context+" "+version);
				req.setContext(context);
//				req.parse();
				handler.handle(req, resp);
			}
		} catch (SocketTimeoutException e) {
			Log.info(e.getMessage());
		} catch(IOException ex) {
			Log.error(ex.getMessage(), ex);
		}  catch(Exception ex) {
			Log.error(ex.getMessage(), ex);
		}
		return false;
		
	}

}
